#ifndef DEF_RSCCOLLECTOR
#define DEF_RSCCOLLECTOR
//#include <pthread.h>

/* nodes type */
typedef struct RListNod {
	pthread_t client_tid;		// clnt thread who hold the resource
	struct clientaddr * client_addr;// client address
	struct  serveraddr * resource;	// the holded resource
	struct RListNod * next;		// next node
		
} RListNod;

/* list of Elt RListNod */
typedef struct {
	struct RListNod * first;	// head of linked list
	struct RListNod * last;		// linked list tail
	int size;			// list size
	pthread_mutex_t mutex;
} RList;

/* list initialisation function */
int rlist_init(RList * list)
{
	if(list == NULL){
		msg("rlist-init","list doesn't exists");
		return EXIT_FAILURE;
	}
	
	list->first = NULL;
	list->last = NULL;
	list->size = 0;

	pthread_mutex_init(& (list->mutex), NULL);
	msg("rlist-init","list initialized successfully");
}

/* list insertion function */
int rlist_insert(RList * list, pthread_t tid, struct clientaddr * client, struct serveraddr * resource)
{
	if(list == NULL){
	 msg("rlist-insert-last","List doesnt exist");
	 return EXIT_FAILURE;
	}
	
	RListNod * newNod = malloc( sizeof(RListNod));
	if (newNod == NULL) {
		msg("rlist-insert-last","malloc error");
		return EXIT_FAILURE;
	}
	// fill the new node data
	newNod->client_tid = tid;
	newNod->client_addr = client;
	newNod->resource = resource;
	
	
	/* case : empty list */
	if ( list->size == 0 )
	{
		list->first = newNod;
		list->last = newNod;
		newNod->next = list->first;
		
	} else 
	{
		(list->last)->next = newNod;
		newNod->next = list->first;
		list->last = newNod;
	}
	
	msg("llist-insert-last","Terminated");
	(list->size)++;
	return EXIT_SUCCESS;
	
}

/* find elt, return resource, and delete node */
int rlist_find(RList * list, pthread_t tid, struct clientaddr ** client_addr, struct serveraddr ** resource)
{
	if(list == NULL) {
	   msg("rlist-insert-last","List doesnt exist");
	   return EXIT_FAILURE;
	}
	
	RListNod * current = list->first;
	RListNod * previous = list->first;
	
	if(list->size == 0){
	 msg("llist-delete-elt","empty list");
	 return EXIT_FAILURE;
	}
	
	while ( ( pthread_equal(tid, current->client_tid) == 0 ) && (current != list->last) ){
		previous = current;
		current = current->next;
	}
	
	if ( (current == list->last) && ( pthread_equal(tid, current->client_tid) == 0 )){
		msg("llist-delete-elt","Elt doesnt exist");
		return EXIT_FAILURE;
	}
	
	
	if(current == list->first) list->first = current->next;
	
	if(current == list->last) list->last = previous;
	
	previous->next = current->next;
	
	// get the resource Addr
	*resource = current->resource;
	// get the client Addr
	*client_addr = current->client_addr;
	
	// delete node
	free(current);
	
	if(list->size == 1) {
		list->first = NULL;
		list->last = NULL;
	}
	
	(list->size)--;	
	msg("llist-delete-elt","Terminated");
	return EXIT_SUCCESS;
}

#endif


